<template>
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>数据筛选</span>
      </div>
    </template>
    <el-form
      ref="form"
      :model="listParams"
      @submit.prevent="handleQuery"
      :disabled="listLoading"
    >
      <el-form-item label="状态">
        <el-select
          v-model="listParams.status"
          class="m-2"
          placeholder="Select"
          size="default"
          clearable
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="管理员名称">
        <el-input
          v-model="listParams.name"
          placeholder="请输入身份昵称"
        />
      </el-form-item>
      <el-form-item>
        <el-button native-type="submit">
          查询
        </el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <el-card>
    <el-button
      type="primary"
      @click="formVisible=true"
    >
      添加管理员
    </el-button>
    <el-table
      :data="list"
      style="width: 100%; margin-top: 1rem;"
      v-loading="listLoading"
    >
      <el-table-column
        prop="id"
        label="ID"
      />
      <el-table-column
        prop="real_name"
        label="姓名"
      />
      <el-table-column
        prop="account"
        label="账号"
      />
      <el-table-column
        prop="roles"
        label="身份"
        min-width="180"
      >
        <template #default="scope">
          <el-space wrap>
            <el-tag
              class="role-tag"
              v-for="(item) in scope.row.roles.split(',')"
              :key="item"
            >
              {{ item }}
            </el-tag>
          </el-space>
        </template>
      </el-table-column>
      <el-table-column
        label="最后一次登录时间"
        prop="last_time"
        min-width="130"
      />
      <el-table-column
        label="最后一次登录IP"
        prop="last_ip"
        min-width="130"
      />
      <el-table-column label="状态">
        <template #default="scope">
          <el-switch
            v-model="scope.row.status"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0"
            active-text="开启"
            inactive-text="关闭"
            inline-prompt
            :loading="scope.row.statusLoading"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        fixed="right"
        min-width="100"
        align="center"
      >
        <template #default="scope">
          <el-button
            type="text"
            @click="handleUpdate(scope.row.id)"
          >
            编辑
          </el-button>
          <el-popconfirm
            title="确认删除吗？"
            @confirm="handleDelete(scope.row.id)"
          >
            <template #reference>
              <el-button type="text">
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- <el-pagination
      v-model:current-page="listParams.page"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="listParams.limit"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalCount"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    /> -->
    <!-- :total="totalCount" // 这个不传，自动作用到根元素，传也行 -->
    <app-pagination
      v-model:page="listParams.page"
      v-model:size="listParams.limit"
      :total-count="totalCount"
      :load-list="loadList"
      :disabled="listLoading"
    />
  </el-card>
  <!--  在组件外部关闭绑定id，然后 @closed="adminId = null" -->
  <!-- 也可以在组件内部关闭， 改 v-model双向绑定属性 -->
  <admin-form
    v-model="formVisible"
    v-model:admin-id="adminId"
  />
</template>

<script lang="ts" setup>
import { changeStatus, deleteAdmins, getAdmins } from '@/api/admin'
import { Admin, IListParams } from '@/api/types/common'
import { onMounted, reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import AdminForm from './AdminForm.vue'

const adminId = ref<number|null>(null) // 编辑项id
const formVisible = ref<boolean>(false) // 对话框
const options = [ // 选择框数据
  {
    value: '',
    label: '全部'
  },
  {
    value: '1',
    label: '显示'
  },
  {
    value: '0',
    label: '不显示'
  }
]
const list = ref<Admin[]>([]) // 列表数据
const listParams = reactive({ // 列表数据查询参数
  page: 1,
  limit: 5,
  name: '',
  roles: '',
  status: '' as IListParams['status'] // 显示指定类型
})
const totalCount = ref(0) // 数据总数
const listLoading = ref(true) // 加载loading

onMounted(() => {
  loadList()
})

// 加载table列表
const loadList = async () => {
  listLoading.value = true
  const data = await getAdmins(listParams).finally(() => {
    listLoading.value = false
  })
  data.list.forEach(item => { // 控制切换状态loading
    item.statusLoading = false
  })
  // console.log('dd', data)
  list.value = data.list
  totalCount.value = data.count
}

// 提交查询表单
const handleQuery = () => {
  loadList()
}

// 修改状态
const handleStatusChange = async (row:Admin) => {
  row.statusLoading = true
  await changeStatus(row.id, row.status).finally(() => {
    row.statusLoading = false
  })
  ElMessage.success(`${row.status === 1 ? '启用' : '禁用'}成功`)
}

// 编辑
const handleUpdate = (id:number) => {
  formVisible.value = true
  adminId.value = id
}

// 删除
const handleDelete = async (id:number) => {
  await deleteAdmins(id)
  ElMessage.success('删除成功')
  loadList()
}

// const handleSizeChange = (val: number) => {
//   // console.log(`${val} items per page`)
//   listParams.limit = val
//   listParams.page = 1
//   loadList()
// }
// const handleCurrentChange = (val: number) => {
//   // console.log(`current page: ${val}`)
//   listParams.page = val
//   loadList()
// }
</script>

<style lang="scss" scoped>
::v-deep .el-form-item{
  display: inline-block;
  margin-right: 1rem;
}
.el-pagination{
  margin-top: 1rem;
  display: flex;
  justify-content: right;
}
</style>
